<?php

$_GET = transcribe($_GET);
$_POST = transcribe($_POST);
$_REQUEST = transcribe($_REQUEST);

function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        if (is_array($value)) {
            $decodedKey = ($isMagic && !$aIsTopLevel) ? stripslashes($key) : $key;
            $decodedValue = transcribe($value, false);
        } else {
            $decodedKey = stripslashes($key);
            $decodedValue = ($isMagic) ? stripslashes($value) : $value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    //过滤表单中的表达式
    is_array($gpcList) && array_walk_recursive($gpcList, 'var_filter');
    return $gpcList;
}

// 过滤表单中的表达式
function var_filter(&$value) {
    // 过滤查询特殊字符
    if (preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|LIKE|NOTLIKE|NOTBETWEEN|NOT BETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i', $value)) {
        $value .= ' ';
    }
}

/**
 * get $_REQUEST value to String
 * @param string $param param
 * @return z(v($param))
 */
function get($param) {
    return z(v($param));
}

/**
 * get $_REQUEST value to String By trim
 * @param string $param param
 * @return z(t(v($param)))
 */
function getTrim($param) {
    return z(t(v($param)));
}

/**
 * get $_REQUEST value to int
 * @param string $param param
 * @param int $default default value, default 0
 * @return int
 */
function getInt($param, $default = 0) {
    return is_int(get($param)) ? intval(get($param)) : $default;
}

/**
 * get $_REQUEST value to bool
 * @param type $param param
 * @return bool
 */
function getBool($param) {
    return toBool(get($param));
}

function toBool($var) {
    if (!is_string($var))
        return (bool) $var;
    switch (strtolower($var)) {
        case '1':
        case 'true':
        case 'on':
        case 'yes':
        case 'y':
            return true;
        default:
            return false;
    }
}

/**
 * get $_REQUEST value to float
 * @param string $param param
 * @param float $default default value, default 0
 * @return 
 */
function getFloat($param, $default = 0) {
    return is_float(get($param)) ? floatval(get($param)) : $default;
}

// render functiones
function render($data = NULL, $layout = NULL, $sharp = 'default') {
    if ($layout == null) {
        if (is_ajax_request()) {
            $layout = 'ajax';
        } elseif (is_mobile_request()) {
            $layout = 'mobile';
        } else {
            $layout = 'web';
        }
    }

    $GLOBALS['layout'] = $layout;
    $GLOBALS['sharp'] = $sharp;

    $layout_file = AROOT . 'view/layout/' . $layout . '/' . $sharp . '.tpl.html';
    if (file_exists($layout_file)) {
        @extract($data);
        require( $layout_file );
    } else {
        $layout_file = CROOT . 'view/layout/' . $layout . '/' . $sharp . '.tpl.html';
        if (file_exists($layout_file)) {
            @extract($data);
            require( $layout_file );
        }
    }
}

function is_ajax_request() {
    $headers = apache_request_headers();
    return (isset($headers['X-Requested-With']) && ( $headers['X-Requested-With'] == 'XMLHttpRequest' )) || (isset($headers['x-requested-with']) && ($headers['x-requested-with'] == 'XMLHttpRequest' ));
}

if (!function_exists('apache_request_headers')) {

    function apache_request_headers() {
        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) == "HTTP_") {
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
                $out[$key] = $value;
            } else {
                $out[$key] = $value;
            }
        }

        return $out;
    }

}

function is_mobile_request() {
    $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';

    $mobile_browser = '0';

    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
        $mobile_browser++;

    if ((isset($_SERVER['HTTP_ACCEPT'])) and ( strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
        $mobile_browser++;

    if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
        $mobile_browser++;

    if (isset($_SERVER['HTTP_PROFILE']))
        $mobile_browser++;

    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
    $mobile_agents = array(
        'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
        'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
        'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
        'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
        'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
        'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
        'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
        'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
        'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
    );

    if (in_array($mobile_ua, $mobile_agents))
        $mobile_browser++;

    if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
        $mobile_browser++;

    // Pre-final check to reset everything if the user is on Windows
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
        $mobile_browser = 0;

    // But WP7 is also Windows, with a slightly different characteristic
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
        $mobile_browser++;

    if ($mobile_browser > 0)
        return true;
    else
        return false;
}

/**
 * Ajax方式返回数据到客户端
 * @param mixed $data 要返回的数据
 * @param String $type AJAX返回数据格式
 * @return void
 */
function ajax($data, $type = '') {
    if (empty($type))
        $type = C('DEFAULT_AJAX_RETURN');
    switch (strtoupper($type)) {
        case 'JSON' :
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            //exit(json_encode($data));
            exit(decodeUnicode(json_encode($data)));
        case 'XML' :
            // 返回xml格式数据
            header('Content-Type:text/xml; charset=utf-8');
            exit(xml_encode($data));
        case 'JSONP':
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            $handler = v(C('VAR_JSONP_HANDLER')) ? v(C('VAR_JSONP_HANDLER')) : C('DEFAULT_JSONP_HANDLER');
            exit($handler . '(' . json_encode($data) . ');');
        case 'EVAL' :
            // 返回可执行的js脚本
            header('Content-Type:text/html; charset=utf-8');
            exit($data);
        default :
            //TODO  修改其他扩展
            exit($data);
        // 用于扩展其他返回格式数据
        //tag('ajax_return', $data);
    }
}

/**
 * XML编码
 * @param mixed $data 数据
 * @param string $root 根节点名
 * @param string $item 数字索引的子节点名
 * @param string $attr 根节点属性
 * @param string $id   数字索引子节点key转换的属性名
 * @param string $encoding 数据编码
 * @return string
 */
function xml_encode($data, $root = 'think', $item = 'item', $attr = '', $id = 'id', $encoding = 'utf-8') {
    if (is_array($attr)) {
        $_attr = array();
        foreach ($attr as $key => $value) {
            $_attr[] = "{$key}=\"{$value}\"";
        }
        $attr = implode(' ', $_attr);
    }
    $attr = trim($attr);
    $attr = empty($attr) ? '' : " {$attr}";
    $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
    $xml .= "<{$root}{$attr}>";
    $xml .= data_to_xml($data, $item, $id);
    $xml .= "</{$root}>";
    return $xml;
}

/**
 * 数据XML编码
 * @param mixed  $data 数据
 * @param string $item 数字索引时的节点名称
 * @param string $id   数字索引key转换为的属性名
 * @return string
 */
function data_to_xml($data, $item = 'item', $id = 'id') {
    $xml = $attr = '';
    foreach ($data as $key => $val) {
        if (is_numeric($key)) {
            $id && $attr = " {$id}=\"{$key}\"";
            $key = $item;
        }
        $xml .= "<{$key}{$attr}>";
        $xml .= (is_array($val) || is_object($val)) ? data_to_xml($val, $item, $id) : $val;
        $xml .= "</{$key}>";
    }
    return $xml;
}

function ajax_echo($info) {
    if (!headers_sent()) {
        header("Content-Type:text/html;charset=utf-8");
        header("Expires: Thu, 01 Jan 1970 00:00:01 GMT");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
    }
    echo $info;
}

function info_page($info, $title = '系统消息') {
    if (is_ajax_request())
        $layout = 'ajax';
    else
        $layout = 'web';

    $data['top_title'] = $data['title'] = $title;
    $data['info'] = $info;

    render($data, $layout, 'info');
}

/**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待时间（秒）
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function redirect($url, $time = 0, $msg = '') {
    //多行URL地址支持
    $url = str_replace(array("\n", "\r"), '', $url);
    if (empty($msg))
        $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
    if (!headers_sent()) {
        // redirect
        if (0 === $time) {
            header('Location: ' . $url);
        } else {
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        exit();
    } else {
        $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0)
            $str .= $msg;
        exit($str);
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
            unset($arr[$pos]);
        $ip = trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
